package com.sky.service.impl;

import com.sky.dto.TimeReportDTO;
import com.sky.entity.Orders;
import com.sky.mapper.DishMapper;
import com.sky.mapper.OrderMapper;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import com.sky.service.ReportService;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class)
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 营业额统计
     * @param timeReportDTO
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(TimeReportDTO timeReportDTO) {
        // 计算出开始时间和结束时间
        List<String> dateList = parserDateList(timeReportDTO);

        // 遍历每一天的日期，计算每一天状态码为已完成的营业额
        List<String> turnoverList = new ArrayList<>();
        for (String date : dateList) {
            // 获取当天的营业额
            String turnover = orderMapper.getTurnoverByDate(date, Orders.COMPLETED);
            turnoverList = ifValueIsNull(turnoverList, turnover);
        }
        // 封装到VO中并返回
        TurnoverReportVO turnoverReportVO = TurnoverReportVO.builder()
                .turnoverList(String.join(",", turnoverList))
                .dateList(String.join(",", dateList))
                .build();
        return turnoverReportVO;
    }

    private List<String> parserDateList(TimeReportDTO timeReportDTO) {
        // 获取开始日期和结束日期
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate beginDate = LocalDate.parse(timeReportDTO.getBegin(), formatter);
        LocalDate endDate = LocalDate.parse(timeReportDTO.getEnd(), formatter);

        // 计算每一天的日期
        List<String> dateList = new ArrayList<>();
        for (LocalDate date = beginDate; !date.isAfter(endDate); date = date.plusDays(1)) {
            dateList.add(date.format(formatter));
        }
        return dateList;
    }

    private List<String> ifValueIsNull(List<String> list, String value) {
        if (value == null) {
            value = "0";
        }
        list.add(value);
        return list;
    }

    /**
     * 用户统计
     * @param timeReportDTO
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(TimeReportDTO timeReportDTO) {
        // 计算出开始时间和结束时间
        List<String> dateList = parserDateList(timeReportDTO);

        // 遍历每一天的日期，计算每一天的用户总量和新增用户
        List<String> totalUserList = new ArrayList<>();
        List<String> newUserList = new ArrayList<>();
        for (String date : dateList) {
            // 获取当天的总用户量
            String totalUser = orderMapper.getTotalUserByDate(date);
            totalUserList = ifValueIsNull(totalUserList, totalUser);
            // 获取当天的新增用户量
            String newUser = orderMapper.getnewUserByDate(date);
            newUserList = ifValueIsNull(newUserList, newUser);
        }
        // 封装到VO中并返回
        UserReportVO userReportVO = UserReportVO.builder()
                .totalUserList(String.join(",", totalUserList))
                .newUserList(String.join(",", newUserList))
                .dateList(String.join(",", dateList))
                .build();
        return userReportVO;
    }

    /**
     * 订单统计
     * @param timeReportDTO
     * @return
     */
    @Override
    public OrderReportVO getOrdersStatistics(TimeReportDTO timeReportDTO) {
        // 计算出开始时间和结束时间
        List<String> dateList = parserDateList(timeReportDTO);
        // 订单总数量
        Integer totalOrderCount = orderMapper.count();
        // 订单有效数量
        Integer validOrderCount = orderMapper.countByStatus(Orders.COMPLETED);

        List<String> orderCountList = new ArrayList<>();
        List<String> validOrderCountList = new ArrayList<>();
        for(String date : dateList){
            // 每日订单数
            String orderCount = orderMapper.countByDate(date);
            // 每日有效订单数(已完成)
            String validOrderCountByDate = orderMapper.countByDateAndStatus(date, Orders.COMPLETED);
            orderCountList.add(orderCount);
            validOrderCountList.add(validOrderCountByDate);
        }
        //订单完成率 = 每日的有效订单数 / 总订单数 * 100%
        Double orderCompletionRate = null;
        if(totalOrderCount != 0){
            orderCompletionRate = ((double) validOrderCount / totalOrderCount);
        }
        // 封装到VO中并返回
        OrderReportVO orderReportVO = OrderReportVO.builder()
                .dateList(String.join(",", dateList))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCountList(String.join(",", orderCountList))
                .validOrderCountList(String.join(",", validOrderCountList))
                .orderCompletionRate(orderCompletionRate)
                .build();
        return orderReportVO;
    }

    /**
     * 销量排名统计
     * @param timeReportDTO
     * @return
     */
    @Override
    public SalesTop10ReportVO getSalesTop10(TimeReportDTO timeReportDTO) {
        List<String> nameList = new ArrayList<>();
        List<String> numberList = new ArrayList<>();
        // 获取菜品名称和销售总数
        List<SalesTop10ReportVO> dishList = dishMapper.getNameAndNumber(timeReportDTO);
        for(SalesTop10ReportVO item : dishList){
            nameList.add(item.getNameList());
            numberList.add(item.getNumberList());
        }
        // 封装到VO中并返回
        SalesTop10ReportVO salesTop10ReportVO = SalesTop10ReportVO.builder()
                .nameList(String.join(",", nameList))
                .numberList(String.join(",", numberList))
                .build();
        return salesTop10ReportVO;
    }

    /**导出近30天的运营数据报表
     * @param response
     **/
    @Override
    public void exportBusinessData(HttpServletResponse response) {
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        //查询概览运营数据，提供给Excel模板文件
        BusinessDataVO businessData = workspaceService.getBusinessData();
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            //基于提供好的模板文件创建一个新的Excel表格对象
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);
            //获得Excel文件中的一个Sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");

            sheet.getRow(1).getCell(1).setCellValue(begin + "至" + end);
            //获得第4行
            XSSFRow row = sheet.getRow(3);
            //获取单元格
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());
            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);
                //准备明细数据
                businessData = workspaceService.getBusinessData();
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }
            //通过输出流将文件下载到客户端浏览器中
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);
            //关闭资源
            out.flush();
            out.close();
            excel.close();

        }catch (IOException e){
            e.printStackTrace();
        }
    }


}
